﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Common;
using ZLCMS.Data.Model;
using ZLCMS.Business;
using NHibernate;
using ZLCMS.Business.Util;
using Newtonsoft.Json;
using ZLCMS.Business.UploadFileInfo;

namespace ZLCMS.Web.SystemManage.Basics.Doc
{
    public partial class Detail : System.Web.UI.Page
    {
        protected FrameHelper _framePage;

        protected CmsKindInfo _kindDB;

        protected CmsDocConfig _config;

        protected void Page_Load(object sender, EventArgs e)
        {
            //初始化DWZ控件
            _framePage = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();

            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                SaveDoc();
            }
        }

        protected void InitializeGlobalValue()
        {

        }

        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                ViewState["typeid"] = Request["typeid"];

                using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    try
                    {
                        string uid = Request["uid"];

                        if (!string.IsNullOrEmpty(uid))
                        {
                            doc_id.Value = uid;

                            CmsDocInfo doc = session.Get<CmsDocInfo>(Int32.Parse(Request["uid"]));

                            CmsTreeDef node = null;
                            if (doc.TypeId != 0)
                            {
                                node = session.Get<CmsTreeDef>((int)doc.TypeId);
                            }
                            if (node != null)
                            {
                                ddTreeControl.SelectedNodeId = node.Id;
                                ddTreeControl.SelectedNodeText = node.Name;
                            }

                            txtTitle.Text = doc.Title;
                            txtName.Text = doc.Name;
                            txtWriter.Text = doc.Author;

                            txtContent.Value = doc.Content;
                            txtSummary.Value = doc.Summary;

                            txtUrl.Text = doc.Url;
                            chkRcmd.Checked = DatabaseHelper.IsTrue(doc.IsRecommend);
                            chkHot.Checked = DatabaseHelper.IsTrue(doc.IsHot);
                            chkHide.Checked = DatabaseHelper.IsTrue(doc.IsHide);
                            tb_order.Text = doc.ShowOrder.ToString();

                            fc_imgurl.Value = doc.ThumbnailUrl;
                            fc_fileurl.Value = doc.AttachmentUrl;

                            txtWebTitle.Text = doc.WebTitle;
                            txtKeyword.Text = doc.WebKeyword;
                            txtDesc.Text = doc.WebDesc;

                            tb_cdate.Text = doc.CreateDate.ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            tb_cdate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                        }

                        doc_kind.Value = (String.IsNullOrEmpty(Request["Kind"]) ? "Default" : Request["Kind"]);

                        _kindDB = session.Get<CmsKindInfo>(doc_kind.Value);
                        _config = session.Get<CmsDocConfig>(_kindDB.ConfigId);

                        //fc_fileurl.FileType = _config.FileType;
                        fc_fileurl.FileFilters = _config.FileType;

                        ddTreeControl.Kind = doc_kind.Value;

                        try
                        {
                            UploadConfig cfg = JsonConvert.DeserializeObject<UploadConfig>(_kindDB.ExtendJasonContent);
                            fc_fileurl.Config = cfg;
                            fc_imgurl.Config = cfg;
                        }
                        catch
                        {
                            throw new Exception("缩略图配置错误");
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    }
                }
            }
        }


        /// <summary>
        /// 保存数据库
        /// </summary>
        protected void SaveDoc()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                string uid = doc_id.Value;

                CmsDocInfo doc;
                if (!string.IsNullOrEmpty(uid))
                {
                    doc = session.Get<CmsDocInfo>(Int32.Parse(uid));
                }
                else
                {
                    doc = new CmsDocInfo();
                }

                if (ddTreeControl.SelectedNodeId == -1)
                {
                    try
                    {
                        doc.TypeId = Convert.ToInt32(ViewState["typeid"]);
                    }
                    catch 
                    {
                    	
                    }
                }
                else
                {
                    doc.TypeId = ddTreeControl.SelectedNodeId;
                }

                doc.Title = txtTitle.Text;
                doc.Name = txtName.Text;
                doc.Author = txtWriter.Text;

                doc.Summary = txtSummary.Value;
                doc.Content = txtContent.Value;

                doc.Url = txtUrl.Text;
                doc.ThumbnailUrl = fc_imgurl.Value;
                doc.AttachmentUrl = fc_fileurl.Value;
                doc.IsHot = DatabaseHelper.ConvertBool(chkHot.Checked);
                doc.IsRecommend = DatabaseHelper.ConvertBool(chkRcmd.Checked);
                doc.IsHide = DatabaseHelper.ConvertBool(chkHide.Checked);
                doc.ShowOrder = int.Parse(tb_order.Text);

                doc.WebTitle = txtWebTitle.Text;
                doc.WebKeyword = txtKeyword.Text;
                doc.WebDesc = txtDesc.Text;

                doc.CreateDate = DateTime.Parse(tb_cdate.Text + " 00:00:00");
                doc.UpdateDate = DateTime.Now;
                doc.OwnerAccount = "admin";
                doc.Kind = doc_kind.Value;
                session.SaveOrUpdate(doc);
                session.Flush();
                doc_id.Value = doc.Id.ToString();
                ReturnCode rc = new ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功!"
                };


                rc.callbackType = "forward";
                rc.forwardUrl = "/SystemManage/Basics/Doc/Detail.aspx?Kind=" + doc_kind.Value + "&tabid=docdetail&typeid=" + ViewState["typeid"];

                if (button_id.Value != "1")
                {
                    rc.forwardUrl += "&uid=" + doc.Id;
                }

                _framePage.Alert(rc);
            }
        }
    }
}
